package com.shadow.baiqun.delegate.receive.locationcheck;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.ColorInt;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.shadow.baiqun.R;
import com.shadow.baiqun.R2;
import com.shadow.baiqun.config.ItemField;
import com.shadow.baiqun.config.ItemType;
import com.shadow.baiqun.delegate.common.ResultConverter;
import com.shadow.baiqun.delegate.receive.adapter.LocationAdapter;
import com.shadow.baiqun.event.RefreshPreOrderListEvent;
import com.shadow.baiqun.view.LocationConfirmDialog;
import com.shadow.baiqun.view.TableHeadView;
import com.shadow.core.delegate.RxShadowDelegate;
import com.shadow.core.net.callback.IError;
import com.shadow.core.net.callback.ISuccess;
import com.shadow.core.net.rx.RxRestClient;
import com.shadow.core.util.toast.ToastUtils;
import com.shadow.ui.progress.sweetalert.DialogLoader;
import com.shadow.ui.progress.sweetalert.IDialogClickListener;
import com.shadow.ui.recycler.MultipleItemEntity;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * @author zy
 * on 2018/5/27
 * 库位核对
 */
public class LocationCheckDelegate extends RxShadowDelegate {
    private static final String ORDER_ID = "orderId";

    public static LocationCheckDelegate create(int orderId) {
        final LocationCheckDelegate contentDelegate = new LocationCheckDelegate();
        final Bundle bundle = new Bundle();
        bundle.putInt(ORDER_ID, orderId);
        contentDelegate.setArguments(bundle);
        return contentDelegate;
    }

    private static final int PAGE_SIZE = 20;
    @BindView(R2.id.toolbar)
    Toolbar mToolbar;
    @BindView(R2.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R2.id.lv_title)
    TableHeadView mHeadView;
    private LocationAdapter mAdapter;
    private int mPreGoodsOrderId;
    private DialogLoader mDialogLoader;
    private int mNextRequestPage = 1;
    private boolean isRequesting = false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mPreGoodsOrderId = bundle.getInt(ORDER_ID);
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_location_check;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
            mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pop();
                }
            });
            mToolbar.setTitle("库位核对");
            mToolbar.inflateMenu(R.menu.print);
            mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    int i = item.getItemId();
                    if (i == R.id.menu_print) {
                        onPrint();
                    }
                    return true;
                }
            });
        }
        List<String> list = new ArrayList<>();
        list.add(getContext().getResources().getString(R.string._part));
        list.add(getContext().getResources().getString(R.string._count));
        list.add(getContext().getResources().getString(R.string._location));
        list.add("状态");
        mHeadView.setHeaders(list);
        mAdapter = new LocationAdapter(getContext(), null);
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadMore();
            }
        }, mRecyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(final BaseQuickAdapter adapter, View view, final int position) {
                MultipleItemEntity entity = (MultipleItemEntity) adapter.getItem(position);
                if (entity != null) {
                    final LocationCheckEntry checkEntry = entity.getField(ItemField.ITEM_OBJ);
                    final LocationConfirmDialog dialog = new LocationConfirmDialog(getContext(),
                            checkEntry.getPartname(),
                            String.valueOf(checkEntry.getStockNum()),
                            String.valueOf(checkEntry.getStockDepotId()));
                    dialog.setOnActionListener(new LocationConfirmDialog.OnActionListener() {
                        @Override
                        public void onCommit(String currentDepId, String depName, int count) {
                            //TODO 确认
                            checkEntry.setDepotname(depName);
                            checkEntry.setStockNum(count);
                            modifyStation(checkEntry.getStockId(), currentDepId, count, checkEntry, position);
                        }
                    });
                    dialog.show();
                }
            }
        });
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setEmptyView(R.layout.view_loading, mRecyclerView);
        if (mAdapter.getEmptyView() != null) {
            mAdapter.getEmptyView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    refresh();
                }
            });
        }
        mDialogLoader = new DialogLoader(getContext());
    }

    private void loadMore() {
        requestData(false);
    }

    public void onPrint() {
        mDisposables.add(RxRestClient.builder()
                .loader(getContext())
                .url("WMS/backstage/collectgoods/updateLabel")
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        if (new ResultConverter().isSucceed(response)) {
                            mDialogLoader.showSuccess("提交成功", "正在打印...", new IDialogClickListener() {
                                @Override
                                public void onClick() {
                                    mDialogLoader.clearDialog();
                                    EventBus.getDefault().post(new RefreshPreOrderListEvent());
                                    pop();
                                }
                            });
                        } else {
                            mDialogLoader.showFailed("提交失败", "打印失败", new IDialogClickListener() {
                                @Override
                                public void onClick() {
                                    mDialogLoader.clearDialog();
                                }
                            });
                        }
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        mDialogLoader.showFailed("提交失败", msg, new IDialogClickListener() {
                            @Override
                            public void onClick() {
                                mDialogLoader.clearDialog();
                            }
                        });
                    }
                })
                .params("prepid", mPreGoodsOrderId)
                .build()
                .unRestGet());
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        refresh();
    }

    /**
     * 请求零件及对应库位
     */
    private void requestData(final boolean isRefresh) {
        mDisposables.add(RxRestClient.builder()
                .url("WMS/backstage/collectgoods/getCollectGoodsPartesListForDepot")
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        mAdapter.setEmptyView(R.layout.view_empty, mRecyclerView);
                        LocationCheckConverter dataConverter = new LocationCheckConverter();
                        dataConverter.setJsonData(response);
                        setData(isRefresh, dataConverter.convert());
                        isRequesting = false;
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        mAdapter.setEmptyView(R.layout.view_empty, mRecyclerView);
                        isRequesting = false;
                    }
                })
                .params("pgid", mPreGoodsOrderId)
                .params("page", mNextRequestPage)
                .params("rows", PAGE_SIZE)
                .build()
                .unRestGet());
    }


    private void modifyStation(int stockId, String depId, int count, final LocationCheckEntry checkEntry, final int position) {
        mDisposables.add(RxRestClient.builder()
                .loader(getContext())
                .url("WMS/backstage/collectgoods/depotCheck")
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        int code = new ResultConverter().getCode(response);
                        if (code == 1) {
                            ToastUtils.showToast(getContext(), "修改成功");
                            mAdapter.setData(position, MultipleItemEntity
                                    .builder().setItemType(ItemType.ITEM_LOCATION_CHECKED)
                                    .setField(ItemField.ITEM_OBJ, checkEntry).build());
                        } else if (code == 2) {
                            ToastUtils.showToast(getContext(), "零件数量不能大于入库系数");
                        }
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        ToastUtils.showToast(getContext(), msg);
                    }
                })
                .params("stockid", stockId)
                .params("depotid", depId)
                .params("stocknum", count)
                .build()
                .unRestGet());
    }

    private void setData(boolean isRefresh, List<MultipleItemEntity> data) {
        mNextRequestPage++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            mAdapter.setNewData(data);
        } else {
            if (size > 0) {
                mAdapter.addData(data);
            }
        }
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd(isRefresh);
        } else {
            mAdapter.loadMoreComplete();
        }
    }

    //刷新
    private void refresh() {
        if (!isRequesting) {
            mNextRequestPage = 1;
            isRequesting = true;
            mAdapter.setEmptyView(R.layout.view_loading, mRecyclerView);
            requestData(true);
        }
    }
}
